<template>
  <div>
    <el-card class="box-card">
      <h2>注册新用户</h2>
      <el-form
        :model="registerForm"
        status-icon
        :rules="registerRules"
        ref="registerFormRef"
        label-placement="left"
        :show-require-mark="true"
        require-mark-placement="right-hanging"
        label-width="auto"
        class="register-from"
        style="max-width: 640px"
      >
        <el-form-item label="用户名" prop="uname">
          <el-input v-model="registerForm.uname" placeholder="请输入用户名" ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="registerForm.password"
            autocomplete="off"
            show-password-title="点击显示密码"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
          <el-input
            type="password"
            v-model="registerForm.password2"
            autocomplete="off"
            show-password-title="点击显示密码"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
      </el-form>
        <el-button type="primary" @click="handleSubmit"
          >注册</el-button
        >
        <el-button @click="handleReset"
          >重置</el-button>
    </el-card>
  </div>
</template>

<script lang="ts">

import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from 'element-plus'

interface RegRuleForm {
  uname: string
  password: string
  password2: string
}

export default {
  setup() {
    // 表单数据
    const registerFormInitValues = {
      uname: 'admin',
      password: '123456',
      password2: '123456',
    };
    const registerForm = ref({ ...registerFormInitValues })
    // 表单验证规则
    const registerRules = reactive<FormRules<RegRuleForm>>({
      uname: [
        { required: true, message: "用户名不能为空！", trigger: "blur" },
      ],
      password: [
        { required: true, message: "密码不能为空！", trigger: "blur" },
      ],
      password2: [
        { required: true, message: "密码不能为空！", trigger: "blur" },
      ],
    });
    // 表单引用
    const registerFormRef = ref<FormInstance | null>(null);

    // 表单提交
    function handleSubmit()  {
      (registerFormRef.value as any).validate((valid: boolean) => {
        if (valid) {
          alert('注册成功');
        } else {
          alert('登录失败');
        }
      });
    };
    function handleReset() {
      // 重置表单功能目前不可用
    };
    // 表单提交
    return {
      registerForm,
      registerRules,
      registerFormRef,
      handleSubmit,
      handleReset
    };
  },
};
</script>

<style scoped>
.box-card {
  margin: auto auto;
  width: 400px;
}
.register-from {
  margin: auto auto;
}
</style>